package com.tender.controller;

import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.tender.BizMsgAssoUserBizService;
import com.tender.dto.BizMsgAssoUserDTO;
import com.tender.common.Result;
import com.tender.integration.config.properties.WebSocketProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/ws/server/bizMsg")
public class BizMsgAssoUserController {

    @Autowired
    private BizMsgAssoUserBizService bizMsgAssoUserBizService;

    @Autowired
    private WebSocketProperties webSocketProperties;

    @PostMapping("/save")
    public Result<Boolean> save(BizMsgAssoUserDTO param) {
        return Result.success(bizMsgAssoUserBizService.save(param));
    }

    @PostMapping("/modify")
    public Result<Boolean> modify(BizMsgAssoUserDTO param) {
        return Result.success(bizMsgAssoUserBizService.modify(param));
    }

    /**
     * 业务消息的推送，需要以这个作为全局统一入口
     * TODO：并发量最大的口子，要不要限流 + 重试机制
     */
    @PostMapping("/push")
    public Result<Boolean> push(@RequestBody BizMsgAssoUserDTO param) {
        RateLimiter rateLimiter = RateLimiter.create(webSocketProperties.getPermitsPerSecond());
        if (!rateLimiter.tryAcquire()) {
            // TODO 抛异常
        }

        return Result.success(bizMsgAssoUserBizService.push(param));
    }

}
